const MYSQL = require("../../sql/mysql");
const DayJs = require("dayjs");
const relativeTime = require("dayjs/plugin/relativeTime");
const Redis = require("../../sql/redis");
const encrypt = require("../../utils/encryption");
const { GetUserBaseInfo } = require("../mange/manage");
let ProjectName = Redis.ProjectName;
var Address6 = require("ip-address").Address6;
// token模块
const JWT = require("../../utils/jwt");
// uuid （用于及时通讯生成会话id）
const { v4: uuidv4 } = require("uuid");
DayJs.extend(relativeTime);
const userSql = "users";
// 用户表
const userSqlName = "users";
// 用户设备表
const deviceSqlName = "user_device";
// 认证信息表
const realInfoSqlName = "user_real_info";
// 用户收货地址表
const userAddressSqlName = "user_address";
// 地址库省份表
const provincesSqlName = null;
// 地址库城市表
const citiesSqlName = null;
// 地址库市区表
const districtsSqlName = null;
// 用户黑名单列表
let BlackUserSqlName = "";
// 动态表
const DynamicSqlNaem = "article";
// 动态点赞记录表
const DynamicLogSqlName = "article_log";
/**
 * 登录
 * @returns {Promise<{code:number,msg:string,logoff_end_date} | {code:number,msg:string}>}
 */
const Login = async (request) => {
  try {
    let ip = request.ip;
    let Body = request.body;
    let address = new Address6(ip).inspectTeredo();
    // 请求IP地址
    let RequestIP = address.client4;
    // 请求时间
    let RequestTime = request.$requestTime;
    // 今日剩余时间戳
    let DayendOfTime = DayJs().endOf("day").valueOf() - RequestTime;
    // 获取登录需要参数
    let { username, password } = Body;
    // 第一步： 校验参数
    if (!username) {
      throw {
        code: 500,
        msg: "用户名不能为空",
      };
    } else if (!password) {
      throw {
        code: 500,
        msg: "密码不能为空",
      };
    }
    // 第一步：该ip地址是否被禁止登录
    let isBannedList = await Redis.lrange(
      `${ProjectName}:IP:LoginBanned`,
      0,
      -1
    );
    let isBanned = isBannedList.some((item) => item === RequestIP);
    if (isBanned) {
      throw {
        code: 500,
        msg: "该ip地址被禁止登录",
      };
    }
    // 第二步：该ip地址是否为多次密码输入错误
    let isThereMultiplePasswordErrorsForIP = await Redis.get(
      `${ProjectName}:IP:DayErrorPasswordNoLogin:${RequestIP}:${username}`
    );
    if (Number(isThereMultiplePasswordErrorsForIP)) {
      throw {
        code: 500,
        msg: "该ip多次密码输入错误,已被禁止登录",
      };
    }
    // 密码是否需要解密
    let ifEncrtpy = false;
    // 密码解密
    if (ifEncrtpy) {
      password = encrypt.decrypt(password);
    }
    let userInfo = null;
    // 初始化标志，表示用户信息是否需要从MySQL查询
    let needFetchFromMySQL = true;
    // 是否允许从Redis中取出用户信息做对比（此举能优化速度但不能保证数据的准确性）
    let RedisGetUserInfo = false;

    // 从Redis中获取根据用户名获取ID
    if (RedisGetUserInfo) {
      // 从Redis中根据ID获取用户信息
      let GetMapUserID = await Redis.get(`${ProjectName}:user:Map:${username}`);
      let RedisUserInfo = await Redis.get(
        `${ProjectName}:user:Info:${GetMapUserID}`
      );
      if (RedisUserInfo) {
        userInfo = JSON.parse(RedisUserInfo);
        needFetchFromMySQL = false; // 如果Redis中有用户信息，则不需要查询MySQL
      }
    }
    // 如果Redis中没有找到所需信息或者信息不完整，则从MySQL获取
    if (needFetchFromMySQL) {
      const Conline = await MYSQL.promise().getConnection();
      // 开始查询MYSQL数据
      let StartMysqlQuery = await Conline.query(
        `SELECT * FROM ${userSql} WHERE username = '${username}'`
      );
      // 查询完毕，释放池连接回池
      await Conline.release();
      // 取出数据
      let userList = StartMysqlQuery[0];
      // 判断用户是否存在
      if (!userList.length) {
        throw {
          code: 500,
          msg: "用户不存在",
        };
      }
      // 取出用户信息
      userInfo = userList[0];
    }
    // 取出用户需要用到的信息
    let {
      avatar, // 头像
      lock, // 是否锁定
      lock_end_date, // 锁定结束时间
      is_user_temporary, // 是否为临时用户
      user_temporary_expire_time, // 临时用户过期时间
      custom_setting, // 管理系统个性化配置
      super_admin, // 是否超级管理员
      roles, // 角色数组
      state, // 状态
      id, // id
    } = userInfo;
    //	超级管理员
    let if_super = Boolean(Number(super_admin));
    // 将用户id和username映射存入Redis，以便下面登录时直接以用户名的方式寻找用户信息
    // await Redis.set(`${ProjectName}:user:Map:${username}`, id);
    // 密码对比
    if (password !== userInfo.password) {
      // let RedisPath = `${ProjectName}:IP:DayErrorPasswordCount:${RequestIP}:${username}`;
      // // 获取今日该IP下的用户名的登录次数
      // let dayErrorPasswordCount = await Redis.get(RedisPath);
      // if (dayErrorPasswordCount === null) {
      //   await Redis.set(RedisPath, 1);
      //   // await Redis.set(RedisPath, 1, DayendOfTime);
      // } else {
      //   // 存入本次登录失败次数
      //   await Redis.incr(RedisPath, 1);
      // }
      // if (!if_super) {
      //   // 每日最大允许密码登录错误次数
      //   let MaxErrorPasswordCount = 10;
      //   // 超过次数则存入Redis中记录，禁止该IP下的用户名再次登录
      //   if (dayErrorPasswordCount > MaxErrorPasswordCount) {
      //     await Redis.set(
      //       `${ProjectName}:IP:DayErrorPasswordNoLogin:${RequestIP}:${username}`,
      //       1,
      //       DayendOfTime
      //     );
      //   }
      // }
      throw {
        code: 500,
        msg: "密码不正确",
      };
    }
    // 账号是否为临时用户 或 账号有效期已到期
    if (is_user_temporary && RequestTime > user_temporary_expire_time) {
      throw {
        code: 500,
        msg: "账号已过期",
      };
    }
    // 账号是否被锁定
    if (lock && lock_end_date > RequestTime) {
      throw {
        code: 500,
        msg: "账号已锁定",
      };
    }
    // 状态检查
    if (state == 0) {
      throw {
        code: 500,
        msg: "黑名单用户",
      };
    } else if (state == 1) {
    } else if (state == 2) {
      throw {
        code: 500,
        msg: "黑名单用户",
      };
    } else if (state == 3) {
      throw {
        code: 500,
        msg: "登录失败,用户正在注销中",
      };
    } else if (state == 4) {
      throw {
        code: 500,
        msg: "登录失败,用户已过期",
      };
    } else if (state == 5) {
      throw {
        code: 500,
        msg: "登录失败,用户已注销",
      };
    }
    if (!if_super) {
      // 获取登录记录，检查今天登录次数
      let userLoginCount = await Redis.get(
        `${ProjectName}:user:DayLoginCount:${id}`
      );
      // 每日最大允许登录次数
      let maxLoginCount = 115;
      // 判断今日登录次数是否超标（超级管理员不受限制）
      if (userLoginCount && userLoginCount > maxLoginCount) {
        throw {
          code: 500,
          msg: `今天登录次数已超过${maxLoginCount}次`,
        };
      }
    }
    // 创建token
    let createToken = JWT.createToken({
      user: id,
      roles,
      username,
      super_admin,
      state,
    });
    let { token, tokenExpires } = createToken;
    // 格式化角色数组
    try {
      roles = roles.split(",");
      if (!Array.isArray(roles)) {
        roles = [];
      } else if (!roles.length) {
        roles = [];
      } else {
        roles = roles.map((item) => Number(item.trim()));
      }
    } catch (error) {
      roles = [];
    }
    userInfo.roles = roles;

    let RedisPipeline = await Redis.pipeline();

    // 添加token到用户Token记录
    RedisPipeline.hset(`${ProjectName}:user:${id}:Token:info:${token}`, {
      create_time: RequestTime,
      expires_time: tokenExpires,
      ip: RequestIP,
      state: 1,
      roles,
    });
    // 添加token到用户Token记录
    RedisPipeline.zadd(`${ProjectName}:user:${id}:Token:List`, [
      RequestTime,
      token,
    ]);

    // 在Redis中添加一次今日登录记录次数
    RedisPipeline.incrby(`${ProjectName}:user:${id}:TodayLoginCount`, 1);
    // 统计用户登录次数
    RedisPipeline.hincrby(
      `${ProjectName}:user:${id}:Statistics:Permanent`,
      "LoginCount",
      1
    );
    // 记录用户最后登录时间
    RedisPipeline.hset(`${ProjectName}:user:${id}:Statistics:Permanent`, {
      LastLoginDate: RequestTime,
      LastLoginIP: RequestIP,
      LastLoginDevice: null,
    });
    // 添加登录记录到Redis
    RedisPipeline.lpush(`${ProjectName}:user:${id}:Statistics:TodayLoginlog`, {
      user: id,
      roles,
      loginTime: RequestTime,
      ip: RequestIP,
      token,
    });
    // 将本次Mysql查询到的用户信息存入Redis
    RedisPipeline.hset(`${ProjectName}:user:${id}:Info:Base`, userInfo);
    // 将本次Mysql查询到的用户信息存入Redis
    RedisPipeline.hset(`${ProjectName}:user:${id}:BaseInfo`, userInfo);
    await RedisPipeline.exec();
    // 接入websocket服务
    await LineWebsocket(id);
    return {
      code: 0,
      msg: "登录成功",
      data: {
        token,
        userInfo,
      },
    };
  } catch (error) {
    console.log("登录失败", error);
    let { code, msg } = error;
    throw {
      code,
      msg,
    };
  }
};
/**
 * 随机免密注册（依靠ip作为唯一，随机注册一个用户,并注册成功直接返回登录后信息）
 * @param {object} params
 */
async function RandomRegister() { }
/**
 * 更新个人信息
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function UpdateInfo(Request, id, update) {
  try {
    let user = Request.$user;

    let body = Request.body;

    // 允许修改的字段
    let allowField = [
      "nickname", // 昵称
      "avatar", // 头像
      "gender", // 性别
      "introduce", // 个人介绍
      "info_background_image", // 个人主页背景图片
      "birth_year", // 出生年
      "birth_month", // 出生月
      "birth_day", // 出生日
      "blood", // 血型
      "address_province", // 所在省
      "address_cities", // 所在城市
      "address_districts", // 所在区县
      "address_town", // 所在城镇
      "address_detail", // 详细地址
      "address_map_longitude", // 地址经度
      "address_map_latitude", // 地图维度
      "address_postal_code", // 邮政编码
    ];
    // 判断body中是否存在不允许的字段,有则剔除
    for (let i = 0; i < allowField.length; i++) {
      let field = allowField[i];
      if (!body[field]) {
        delete body[field];
      }
    }
    // 获取MYSQL 连接
    let connection = await MYSQL.promise().getConnection();
    // 开始事务
    await connection.beginTransaction();
    // 更新用户信息
    let updateResult = await connection.query(
      `
		UPDATE ${userSqlName} SET ? WHERE id = ${user}
		`,
      body
    );
    // 取出更新结果
    let affectedRows = updateResult[0].affectedRows;

    if (affectedRows) {
      // 提交事务
      await connection.commit();
      // 返回结果
      return {
        code: 0,
        msg: "修改成功",
      };
    } else {
      // 回滚事务
      await connection.rollback();
      // 返回结果
      throw {
        code: 500,
        msg: "修改失败,未修改任何信息",
      };
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 获取个人信息
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function GetInfo(Request) {
  try {
    let user = Request.$user;
    let userInfo = await GetUserBaseInfo(user);
    return {
      code: 0,
      msg: "获取成功",
      data: userInfo,
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 获取账号注销状态
 * @param {object} params 参数信息
 * @param {string} params.user 用户id
 * @returns {Promise<{code:number,msg:string,logoff_end_date} | {code:number,msg:string}>}
 */
async function GetErase(Request) {
  try {
    let user = Request.$user;
    let userInfo = await GetUserBaseInfo(user);
    let { data } = userInfo;
    let { id, super_admin, real_state, state } = data;
    // real_state 状态说明：  0：未注销   1：注销中    2：已注销
    return {
      code: 0,
      msg: "获取成功",
      data: {
        id,
        super_admin,
        real_state,
        logoff_start_date: null,
        logoff_end_date: null,
        state,
      },
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 申请注销
 * @param {object} params 参数信息
 * @param {string} params.user 用户id
 * @returns {Promise<{code:number,msg:string,logoff_end_date} | {code:number,msg:string}>}
 */
async function Erase(Request) {
  try {
    let user = Request.$user;
    // 是否允许注销
    let logoff_status = true;
    // 注销等待时间
    let logoff_wait_date = 86400000 * 15;
    // 当前时间
    let date_now = Request.$requestTime;
    if (!logoff_status) {
      throw {
        code: 500,
        msg: "注销失败,禁止用户注销",
      };
    }

    let { data: userInfo } = await GetUserBaseInfo(user);

    let { state, super_admin } = userInfo;

    if (super_admin) {
      throw {
        code: 500,
        msg: "超级管理员禁止注销",
      };
    } else if (state == 3) {
      throw {
        code: 500,
        msg: "注销失败,用户正在注销",
      };
    } else if (state == 5) {
      throw {
        code: 500,
        msg: "注销失败,用户已注销",
      };
    }

    // 注销开始时间
    let logoff_start_date = date_now;
    // 注销结束时间
    let logoff_end_dete = null;
    // 新的用户state
    let new_user_state = null;
    // 判断注销等待时间,如果为0，则立即注销
    if (logoff_wait_date) {
      // 延迟注销
      logoff_end_dete = date_now + logoff_wait_date;
      new_user_state = 3;
    } else {
      // 立即注销
      logoff_end_dete = date_now.valueOf();
      new_user_state = 5;
    }
    // 获取MYSQL池链接
    let Conline = await MYSQL.promise().getConnection();
    // 开启MYSQL 事务
    await Conline.beginTransaction();
    // 更新用户状态
    let updateUserInfo = await Conline.query(
      `UPDATE users SET ? WHERE id = ${user}`,
      {
        logoff_start_date,
        logoff_end_dete,
        state: new_user_state,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();

    let affectedRows = updateUserInfo[0].affectedRows;

    if (affectedRows) {
      // 提交事务
      await Conline.commit();
      return {
        code: 0,
        msg: "注销成功",
      };
    } else {
      // 回滚
      await Conline.rollback();
      throw {
        code: 500,
        msg: "注销失败,未知错误",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 取消注销
 * @param {Object} params
 * @returns {Promise<{code:number,msg:string,logoff_end_date} | {code:number,msg:string}>}
 */
async function CancelErase(Request) {
  try {
    let user = Request.$user;
    if (!user) {
      throw {
        code: 500,
        msg: "用户id不能为空",
      };
    }
    // 查询用户
    let { data: userInfo } = await GetUserBaseInfo(user);

    let { state } = userInfo;

    if (state == 5) {
      throw {
        code: 500,
        msg: "撤销失败,用户已注销",
      };
    }
    if (state == 3) {
      // 获取MYSQL池链接
      let Conline = await MYSQL.promise().getConnection();
      // 开启MYSQL 事务
      await Conline.beginTransaction();
      // 更新用户状态
      let updateUserInfo = await Conline.query(
        `UPDATE users SET ? WHERE id = ${user}`,
        {
          logoff_start_date: null,
          logoff_end_dete: null,
          state: 1,
        }
      );
      // 查询完毕，释放池连接回池
      await Conline.release();
      let affectedRows = updateUserInfo[0].affectedRows;
      if (affectedRows) {
        // 提交事务
        await Conline.commit();
        return {
          code: 0,
          msg: "撤销成功",
        };
      } else {
        // 回滚
        await Conline.rollback();
        throw {
          code: 500,
          msg: "撤销失败,未知错误",
        };
      }
    } else {
      throw {
        code: 500,
        msg: "撤销失败,用户状态不支持撤销",
      };
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * token校验，并返回用户信息
 * @param {object} params 配置对象
 * @param {object} params.token token
 * @return {promise<{code:string,msg:string}>}
 */
async function CheckToken(Request) {
  try {
    let token = Request.$token;
    // 使用JWT解构出用户信息
    let { data } = JWT.verify(token);
    let { user } = data;
    let userInfo = await Redis.get(`${ProjectName}:user:Info:${user}`);
    if (!userInfo) {
      throw {
        code: 500,
        msg: "操作失败,token不存在",
      };
    } else {
      return {
        code: 0,
        msg: "校验成功",
        data: JSON.parse(userInfo),
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 收货地址列表
 * @param {object} params 配置对象
 * @param {object} params.page 页码
 * @return {promise<{code:string,msg:string}>}
 */
async function AddressList(Request) {
  try {
    let user = Request.$user;

    let query = Request.query;

    let { page = 1, limit = 10 } = query;

    limit = limit < 1 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;

    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    }

    let ListQuery = `

		SELECT 
		userAddress.*,
		provinces.name AS provinceName,
		cities.name AS citiesName,
		districts.name AS districtsName,
		userAddress.state
		
		FROM user_address AS userAddress

		JOIN address_provinces AS provinces 
		ON userAddress.province = provinces.code 
		AND provinces.state = 1

		JOIN address_cities AS cities 
		ON userAddress.cities = cities.code 
		AND cities.parent = provinces.code
		AND cities.state = 1

		JOIN address_districts AS districts 
		ON userAddress.districts = districts.code 
		AND districts.parent = cities.code
		AND districts.state = 1
		
		WHERE user = '${user}'

		LIMIT ${(page - 1) * limit + "," + page * limit}

        `;
    // 获取MYSQL池链接
    const Connection = await MYSQL.promise().getConnection();
    //
    let mysqlResult = await Connection.query(ListQuery);

    // 查询完毕，释放池连接回池
    await Connection.release();

    let list = mysqlResult[0];

    return {
      code: 0,
      msg: "获取成功",
      data: {
        page,
        limit,
        list,
      },
    };
  } catch (error) {
    console.log(error);
    throw {
      code: 500,
      msg: "获取失败",
    };
  }
}
/**
 * 添加收货地址
 * @param {object} params 配置对象
 * @param {object} params.token token
 * @return {promise<{code:string,msg:string}>}
 */
async function AddAddress(Request) {
  try {
    let user = Request.$user;

    let Body = Request.body;

    let {
      recipient, // 收件人
      mobile, // 联系号码
      province, // 省份
      cities, // 城市
      districts, // 区县
      detail, // 详细地址
    } = Body;

    if (!recipient) {
      throw {
        code: 500,
        msg: "添加失败,缺少收件人",
      };
    } else if (!mobile) {
      throw {
        code: 500,
        msg: "添加失败,缺少联系号码",
      };
    } else if (!province) {
      throw {
        code: 500,
        msg: "添加失败,缺少省份",
      };
    } else if (!cities) {
      throw {
        code: 500,
        msg: "添加失败,缺少城市",
      };
    } else if (!districts) {
      throw {
        code: 500,
        msg: "添加失败,缺少区县",
      };
    } else if (!detail) {
      throw {
        code: 500,
        msg: "添加失败,缺少详细地址",
      };
    }
    // 获取MYSQL池链接
    const Connection = await MYSQL.promise().getConnection();
    // 执行MYSQL
    let INSERTResult = await Connection.query(
      `INSERT INTO user_address SET ?`,
      {
        user, // 用户
        recipient, // 收件人
        mobile, // 联系号码
        province, // 省份
        cities, // 城市
        districts, // 区县
        detail, // 详细地址
        if_default: 0, // 默认
      }
    );
    // 查询完毕，释放池连接回池
    await Connection.release();
    let affectedRows = INSERTResult[0].affectedRows;
    if (affectedRows) {
      return {
        code: 0,
        msg: "添加成功",
      };
    } else {
      throw {
        code: 500,
        msg: "添加失败",
      };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 更新地址
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function UpdateAddress(params = {}) {
  try {
    let { id, user, data } = params;
    id = id || data?.id || false;
    if (!user) {
      throw {
        code: 500,
        msg: "user不能为空",
      };
    } else if (!id) {
      throw {
        code: 500,
        msg: "id不能为空",
      };
    } else if (!data) {
      throw {
        code: 500,
        msg: "data不能为空",
      };
    }
    let {
      tag, // 标签
      recipient, // 收件人
      mobile, // 联系号码
      province, // 省份
      cities, // 城市
      districts, // 区县
      detail, // 详细地址
      map_longitude, // 经纬度
      map_latitude, // 经纬度
      often = false,
    } = data;

    if (!recipient) {
      throw {
        code: 500,
        msg: "添加失败,缺少收件人",
      };
    } else if (!mobile) {
      throw {
        code: 500,
        msg: "添加失败,缺少联系号码",
      };
    } else if (!province) {
      throw {
        code: 500,
        msg: "添加失败,缺少省份",
      };
    } else if (!cities) {
      throw {
        code: 500,
        msg: "添加失败,缺少城市",
      };
    } else if (!districts) {
      throw {
        code: 500,
        msg: "添加失败,缺少区县",
      };
    } else if (!detail) {
      throw {
        code: 500,
        msg: "添加失败,缺少详细地址",
      };
    }

    // 如果本次添加地址时是需要添加一个默认地址,那么需要首先将所有地址的默认值取消
    if (often) {
      await setDefaultAddress({
        user,
        often: false,
      });
    }
    // 添加新地址的数据
    let updateData = {
      tag, // 标签
      recipient, // 收件人
      mobile, // 联系号码
      province, // 省份
      cities, // 城市
      districts, // 区县
      detail, // 详细地址
      map_longitude, // 经纬度
      map_latitude, // 经纬度
      often: String(Number(often)), // 默认
    };
    // 执行MYSQL
    await MYSQL.promise().query(`UPDATE ${SQLName} SET ?`, updateData);
    // 返回结果
    return {
      code: 0,
      msg: "更新成功",
    };
  } catch (error) {
    throw {
      code: 500,
      msg: "更新失败,未知错误",
    };
  }
}
/**
 * 删除收货地址
 * @param {object} params
 * @param {string} params.id 地址id
 * @param {string} params.user 用户id
 */
async function deleteAddress(Request) {
  try {
    let user = Request.$user;
    let Body = Request.body;
    let { id } = Body;
    if (!id) {
      throw {
        code: 500,
        msg: "id不能为空",
      };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    // 开始更新MYSQL
    let updateUserInfo = await Conline.query(
      `UPDATE user_address SET ? WHERE id = ${id} AND user = ${user}`,
      {
        state: 0,
      }
    );
    // 查询完毕，释放池连接回池
    await Conline.release();

    let affectedRows = updateUserInfo[0].affectedRows;

    if (affectedRows) {
      return {
        code: 0,
        msg: "删除成功",
      };
    } else {
      throw {
        code: 500,
        msg: "删除失败,没有删除到记录",
      };
    }
  } catch (error) {
    throw {
      code: 500,
      msg: "删除失败,未知错误",
    };
  }
}
/**
 * 设置默认地址
 * @param {object} params
 * @param {string} params.user  用户id
 * @param {string} params.id  地址记录id
 * @param {string} params.often 默认地址，falst取消默认  true设置默认
 */
async function SetDefaultAddress(Request) {
  try {
    let user = Request.$user;

    let Body = Request.body;

    let { id } = Body;
    if (!id) {
      throw {
        code: 500,
        msg: "id不能为空",
      };
    }
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();

    // 开始更新MYSQL , 设置所有地址为非默认
    await Conline.query(`
			UPDATE user_address SET
			if_default = IF(id = ${id}, 1, 0)
			WHERE user = ${user}
		`);

    // 查询完毕，释放池连接回池
    await Conline.release();

    return {
      code: 0,
      msg: "设置成功",
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 清空收货地址
 * @param {object} params
 * @return {promise<{code:string,msg:string}>}
 */
async function EmptyAddress(Request) {
  try {
    let user = Request.$user;
    // 获取Mysql池链接
    const Conline = await MYSQL.promise().getConnection();
    await Conline.query(`UPDATE user_address SET ? WHERE user = ${user}`, {
      state: 0,
    });
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "清空成功",
    };
  } catch (error) {
    throw {
      code: 500,
      msg: "清空失败",
    };
  }
}
/**
 * 退出登录
 * @return {promise<{code:string,msg:string}>}
 */
async function loginout(Request) {
  try {
    let token = Request.$token;
    let user = Request.$user;
    return { code: 0, msg: "登出成功" };
  } catch (error) {
    throw { code: 500, msg: "退出失败" };
  }
}
/**
 * 即时消息会话置顶
 * @return {promise<{code:string,msg:string}>}
 */
async function MessageSetTop(Request) {
  try {
    let user = Request.$user;
  } catch (error) { }
}
/**
 * 即时消息取消置顶
 * @return {promise<{code:string,msg:string}>}
 */
async function MessageCancelTop(Request) {
  try {
    let user = Request.$user;

    let Body = Request.body;

    let { id } = Body;
  } catch (error) { }
}
/**
 * 删除即时消息(聊天记录会删除)
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteMessage(Request) {
  try {
    // 用户
    let user = Request.$user;
    // body
    let body = Request.body;
    // 会话id（用户id）
    let { id } = body;
    if (!id) {
      throw { code: 500, msg: "id不能为空" };
    }

    // 查询Redis中是否存在该会话

    let RedisPath = ``;
  } catch (error) {
    throw error;
  }
}
/**
 * 创建会话
 * @return {promise<{code:string,msg:string}>}
 */
async function CreatedMessage(from_user, to_user) {
  try {
    let ProjectName = "TardeAdmin";
    // 在发送者会话管理中查询单聊是否存在与该用户的会话
    let from_user_message = await Redis.hGet(`${ProjectName}:Message:alone`);
  } catch (error) { }
}
/**
 * 创建群聊
 * @return {promise<{code:string,msg:string}>}
 */
async function CreatedGroupMessage(Request) {
  try {
    let user = Request.$user;

    let body = Request.body;

    let { name = "测试群聊名称" } = body;

    // 会话时间
    let created_time = new Date().getTime();
    // 成员数组
    let members = [user];
    // 群组ID
    let MessageId = uuidv4();
    // let RedisGroupMembersPath = `${ProjectName}:Messaging:Group:${GroupId}:Members`
    let membersFormat = members.map((item) => {
      return {
        user: Number(item),
        state: 1,
        created_time,
      };
    });
    // 会话RedisPath
    let RedisConversationPath = `${ProjectName}:Messaging:Conversation:${MessageId}:Info`;
    // 会话ID
    await Redis.hSet(RedisConversationPath, "id", GroupId);
    // 会话名称
    await Redis.hSet(RedisConversationPath, "name", name);
    // 会话类型
    await Redis.hSet(RedisConversationPath, "type", "Group");
    // 会话群组类型
    await Redis.hSet(RedisConversationPath, "GroupType", "");
    // 会话成员
    await Redis.hSet(
      RedisConversationPath,
      "members",
      JSON.stringify(membersFormat)
    );
    // 会话公告
    await Redis.hSet(RedisConversationPath, "notice", "");
    // 会话群组人数上限
    await Redis.hSet(RedisConversationPath, "type", "Group");
    // 群组创建用户
    await Redis.hSet(RedisConversationPath, "created_user", user);
    // 成员数组
    await Redis.hSet(
      RedisConversationPath,
      "members",
      JSON.stringify(membersFormat)
    );
    // 成员人数
    await Redis.hSet(
      RedisConversationPath,
      "membersCount",
      membersFormat.length
    );
    // 会话创建时间
    await Redis.hSet(RedisConversationPath, "created_time", created_time);
    // 会话备注
    await Redis.hSet(RedisConversationPath, "comment", 1);
    // 会话状态
    await Redis.hSet(RedisConversationPath, "state", 1);

    return { code: 0, msg: "创建成功" };
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "创建失败" };
  }
}
/**
 * 创建群聊
 * @return {promise<{code:string,msg:string}>}
 */
async function CreatedGroup(Request) {
  try {
    return true;
  } catch (error) {
    return false;
  }
}
/**
 * 群聊踢出成员
 * @return {promise<{code:string,msg:string}>}
 */
async function KickMember() { }
/**
 * 解散群聊
 * @return {promise<{code:string,msg:string}>}
 */
async function DisbandGroup() { }
/**
 * 发送即时消息
 * @return {promise<{code:string,msg:string}>}
 */
async function SendMessage(Request) {
  try {
    // 会话状态：   1：正常    0：禁止   2：警告   3：删除
    let body = Request.body;
    // 发送者
    let from_user = Request.$user;
    let {
      // 本地id
      localhost_id,
      // 会话id,如果是单聊，则不需要该参数
      message_id,
      // 会话类型 user:单聊
      message_type,
      // 接收者
      to_user,
      value,
    } = body;

    // 查询发送者是否被禁言
    let SpeakOut = await CheckUserIsMute(from_user);
    if (SpeakOut) {
      throw { code: 500, msg: "发布失败,您已被禁言" };
    }

    // // 查询发送者是否被接收者拉入黑名单
    // let to_user_black_list = await Redis.lRange(`${ProjectName}:Messaging:blackList:${to_user}`,0,-1)

    // let ifBlack = to_user_black_list.map(i=>JSON.parse(i))
    // .some(i=>i.from_user == from_user && i.to_user == to_user)

    // if(ifBlack){
    // 	throw {code:500,msg:"您已被拉黑"}
    // }

    // // 查询发送者是否拥有接收者的好友关系
    // let from_user_friend_list = await Redis.lRange(`${ProjectName}:Messaging:contactList:${from_user}`,0,-1)

    // let ifFriend = from_user_friend_list
    // .map(i=>JSON.parse(i))
    // .some(i=>i.from_user == from_user && i.to_user == to_user)

    // if(!from_user_friend_list.length || !ifFriend){
    // 	throw {code:500,msg:"您没有好友关系"}
    // }
    if (!to_user) {
      throw { code: 500, msg: "接收者不能为空" };
    } else if (!value) {
      throw { code: 500, msg: "消息内容不能为空" };
    }

    // 会话时间
    let created_time = new Date().getTime();
    // 会话类型
    // let MessageType = Number(type)

    // 消息内容 违禁检测

    // 单聊会话
    if (message_type == "user") {
      if (!to_user) {
        throw { code: 500, msg: "接收者不能为空" };
      }
      // 是否需要新建会话
      let ifNewCreatedConversation = false;
      // 是否新建会话id
      let ifNewCreated = false;
      // 会话id
      let MessageId = null;
      // 发布者会话
      let FromUserAloneRedisPath = `${ProjectName}:Messaging:AloneMap:${from_user}:${to_user}:Info`;
      // 接收者会话
      let ToUserAloneRedisPath = `${ProjectName}:Messaging:AloneMap:${to_user}:${from_user}:Info`;

      // 寻找发布者的单聊会话中是否已有会话id
      let FromUserAloneRedisMessageId = await Redis.hGet(
        FromUserAloneRedisPath,
        "MessageId"
      );
      let ToUserAloneRedisMessageId = await Redis.hGet(
        ToUserAloneRedisPath,
        "MessageId"
      );

      if (FromUserAloneRedisMessageId) {
        MessageId = FromUserAloneRedisMessageId;
        console.log("发布者已有会话ID");
        if (!ToUserAloneRedisMessageId) {
          // 如果发布者有会话ID，但是接收者没有，那么需要在接收者处新建一个会话
          await Redis.hSet(ToUserAloneRedisPath, "MessageId", MessageId);
          await Redis.hSet(ToUserAloneRedisPath, "Notdisturb", 0);
        }
      } else {
        // 如果接收者有会话ID，但是发布者没有，那么需要在发布者处新建一个会话ID
        if (ToUserAloneRedisMessageId) {
          console.log("接收者已有会话ID");
          MessageId = ToUserAloneRedisMessageId;
          // 发布者创建会话映射，会话映射主要是用户对于该会话的设置，比如：会话是否免打扰
          await Redis.hSet(FromUserAloneRedisPath, "MessageId", MessageId);
          await Redis.hSet(FromUserAloneRedisPath, "Notdisturb", 0);
        } else {
          MessageId = uuidv4();
          ifNewCreated = true;
          ifNewCreatedConversation = true;
          console.log("发布者和接收者都没有ID,本次会话需要新建");
        }
      }

      // 会话Redis地址
      let RedisConversationPath = `${ProjectName}:Messaging:Conversation:${MessageId}`;

      if (ifNewCreated) {
        // 新建会话
        await Redis.hSet(`${RedisConversationPath}:Info`, "id", MessageId);
        await Redis.hSet(`${RedisConversationPath}:Info`, "type", "alone");
        await Redis.hSet(
          `${RedisConversationPath}:Info`,
          "created_user",
          created_time
        );
        await Redis.hSet(
          `${RedisConversationPath}:Info`,
          "from_user",
          from_user
        );
        await Redis.hSet(`${RedisConversationPath}:Info`, "to_user", to_user);
        await Redis.hSet(`${RedisConversationPath}:Info`, "state", 1);
        // 新建单聊会话映射，会话映射主要是用户对于该会话的设置，比如：会话是否免打扰
        // 发布者 ========================
        // 会话ID
        await Redis.hSet(FromUserAloneRedisPath, "MessageId", MessageId);
        // 是否免打扰
        await Redis.hSet(FromUserAloneRedisPath, "Notdisturb", 0);
        // 阅读的消息记录长度
        await Redis.hSet(FromUserAloneRedisPath, "Notdisturb", 0);
        // 推送的消息记录长度
        await Redis.hSet(FromUserAloneRedisPath, "Notdisturb", 0);
        // 接收者 ========================
        // 会话ID
        await Redis.hSet(ToUserAloneRedisPath, "MessageId", MessageId);
        // 是否免打扰
        await Redis.hSet(ToUserAloneRedisPath, "Notdisturb", 0);
        // 阅读的消息记录长度
        await Redis.hSet(ToUserAloneRedisPath, "Notdisturb", 0);
        // 推送的消息记录长度
        await Redis.hSet(ToUserAloneRedisPath, "Notdisturb", 0);
      } else {
        // 会话配置Redis地址
        let RedisConversationConfigPath = `${RedisConversationPath}:Info`;
        // 查看会话配置,是否允许进行会话
        let ConversationConfig = await Redis.hGetAll(
          RedisConversationConfigPath
        );
        let {
          state: ConversationState,
          from_user: ConversationFromUser,
          to_user: ConversationToUser,
        } = ConversationConfig;

        // 检验发送者和接收者是否一致
        if (
          ConversationFromUser != from_user ||
          ConversationToUser != to_user
        ) {
          throw { code: 500, msg: "会话配置错误" };
        }
        // 检验会话状态是否正常
        if (ConversationState != 1) {
          throw { code: 500, msg: "会话已关闭" };
        }
      }
      if (ifNewCreatedConversation) {
        await Redis.rPush(
          `${ProjectName}:user:MessageList:${to_user}`,
          MessageId
        );
        await Redis.rPush(
          `${ProjectName}:user:MessageList:${from_user}`,
          MessageId
        );
      } else {
        // 查询发布者会话中是否存在该会话id
        let FromUserMessageListRedisPath = `${ProjectName}:user:MessageList:${from_user}`;
        let FromUserMessageList = await Redis.lRange(
          FromUserMessageListRedisPath,
          0,
          -1
        );
        // 接收者会话列表
        let ToUserMessageListRedisPath = `${ProjectName}:user:MessageList:${to_user}`;
        let ToUserMessageList = await Redis.lRange(
          ToUserMessageListRedisPath,
          0,
          -1
        );
        let ifFromUserSome = FromUserMessageList.some((i) => i == MessageId);
        let ifToUserSome = ToUserMessageList.some((i) => i == MessageId);
        if (!ifFromUserSome) {
          await Redis.rPush(
            `${ProjectName}:user:MessageList:${from_user}`,
            MessageId
          );
        }
        if (!ifToUserSome) {
          await Redis.rPush(
            `${ProjectName}:user:MessageList:${to_user}`,
            MessageId
          );
        }
      }
      // 向会话中添加消息
      await Redis.rPush(
        `${RedisConversationPath}:MessageList`,
        JSON.stringify({
          MessageId: MessageId,
          type: "Alone",
          from_user,
          to_user,
          type: message_type,
          value,
          images: [],
          video: [],
          created_time,
          state: 0,
          quote: null,
        })
      );

      return { code: 0, msg: "发送成功" };
    }
    // 群聊
    if (message_type == "group") {
    }

    return { code: 0, msg: "发送成功" };
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 加载即时消息会话记录（非查询聊天记录）
 * @return {promise<{code:string,msg:string}>}
 */
async function GetMessageHistory(Request) {
  try {
    let from_user = Request.$user;
    let to_user = Request.query.to_user;

    let query = Request.query;

    let { page = 1, limit = 10 } = query;

    // 如果page 小于1 则为1，
    page = page < 1 ? (page = 1) : page;

    // 如果limit 小于1 则为1
    limit = limit < 1 ? (limit = 1) : limit;

    if (!to_user) {
      throw { code: 500, msg: "会话用户id不能为空" };
    }
    // Redis存储路径
    let RedisPath = `${ProjectName}:user:InstantMessaging:${from_user}:${to_user}`;

    // 获取记录数据总数
    let count = await Redis.lLen(RedisPath);

    // 获取总页数
    let pages = Math.ceil(count / limit);

    // 分页查询消息记录
    let RedisMessageList = await Redis.lRange(
      RedisPath,
      (page - 1) * limit,
      page * limit
    );

    return {
      code: 0,
      msg: "获取成功",
      data: {
        from_user,
        to_user,
        list: RedisMessageList.map((item) => JSON.parse(item)),
        page,
        pages,
        limit,
        count,
      },
    };
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 获取即时消息列表
 * @return {promise<{code:string,msg:string}>}
 */
async function GetMessageList(Request) {
  try {
    let user = Request.$user;
    let list = [
      {
        userInfo: {
          username: "马云",
          avatar:
            "https://img1.baidu.com/it/u=1350435684,987731884&fm=253&fmt=auto&app=138&f=JPEG?w=60&h=60",
        },
      },
      {
        userInfo: {
          username: "张家辉",
          avatar:
            "https://img0.baidu.com/it/u=52911852,2020613831&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400",
        },
      },
      {
        userInfo: {
          username: "刘德华",
          avatar:
            "https://img0.baidu.com/it/u=2958612378,1778105733&fm=253&fmt=auto&app=138&f=JPEG?w=60&h=60",
        },
      },
      {
        userInfo: {
          username: "高启强",
          avatar:
            "https://img2.baidu.com/it/u=115994466,1471295685&fm=253&fmt=auto&app=138&f=JPEG?w=60&h=60",
        },
      },
      {
        userInfo: {
          username: "高启盛",
          avatar:
            "https://img0.baidu.com/it/u=3056998931,900400438&fm=253&fmt=auto&app=138&f=JPEG?w=60&h=60",
        },
      },
    ];
    return {
      code: 0,
      msg: "获取成功",
      data: {
        user,
        list,
      },
    };
    // let user = Request.$user;
    // // Redis存储路径
    // let RedisPath = `${ProjectName}:user:MessageList:${user}`;
    // let RedisMessageList = await Redis.lRange(RedisPath, 0, -1);
    // let list = await Promise.all(
    //   RedisMessageList.map(async (MessageId) => {
    //     let Path = `${ProjectName}:Messaging:Conversation:${MessageId}:Info`;
    //     let Conversation = await Redis.hGetAll(Path);
    //     let ConversationType = Conversation.type;
    //     let returnData = null;
    //     if (ConversationType == "alone") {
    //       let { from_user, to_user, state, id, type } = Conversation;
    //       let userConversationInfoPath = null;

    //       let avatar =
    //         "https://img2.baidu.com/it/u=1543272741,4126886972&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1719853200&t=2eef8ab3f304c0feebd5c00a50cc2963";

    //       let userInfo = { avatar };
    //       if (user == from_user) {
    //         userInfo.user = to_user;
    //         userConversationInfoPath = `${ProjectName}:Messaging:AloneMap:${user}:${to_user}:Info`;
    //       } else if (user == to_user) {
    //         userConversationInfoPath = `${ProjectName}:Messaging:AloneMap:${from_user}:${user}:Info`;
    //         userInfo.user = from_user;
    //       }
    //       let userConversationInfo = await Redis.hGetAll(
    //         userConversationInfoPath
    //       );

    //       let { Notdisturb } = userConversationInfo;
    //       Notdisturb = Boolean(Number(Notdisturb)) ?? false;
    //       let RedisPath = `${ProjectName}:Messaging:Conversation:${MessageId}:MessageList`;
    //       // 消息记录页码
    //       let Page = 1;
    //       // 消息记录每页查询数量
    //       let limit = 10;
    //       // 消息记录开始索引
    //       let StartIndex = (Page - 1) * limit;
    //       // 消息记录结束索引
    //       let EndIndex = Page * limit - 1;
    //       let List = await Redis.lRange(RedisPath, StartIndex, EndIndex);
    //       let MessageList = List.map((i) => {
    //         i = JSON.parse(i);

    //         let { from_user, to_user } = i;

    //         if (from_user == user) {
    //           i.direction = 1;
    //         }
    //         if (to_user == user) {
    //           i.direction = 0;
    //         }
    //         delete i.to_user;
    //         delete i.from_user;
    //         delete i.state;
    //         delete i.quote;
    //         return i;
    //       });
    //       returnData = {
    //         id,
    //         Notdisturb,
    //         type,
    //         userInfo,
    //         MessageList,
    //         state,
    //       };
    //     }
    //     return returnData;
    //   })
    // );
    // return {
    //   code: 0,
    //   msg: "获取成功",
    //   data: {
    //     user,
    //     list,
    //   },
    // };
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 获取通讯录列表
 * @return {promise<{code:string,msg:string}>}
 */
async function GetMailList(Request) {
  try {
    let list = [
      {
        index: "A",
        data: [
          "阿坝",
          "阿拉善",
          "阿里",
          "安康",
          "安庆",
          "鞍山",
          "安顺",
          "安阳",
          "澳门",
        ],
      },
      {
        index: "B",
        data: [
          "北京",
          "白银",
          "保定",
          "宝鸡",
          "保山",
          "包头",
          "巴中",
          "北海",
          "蚌埠",
          "本溪",
          "毕节",
          "滨州",
          "百色",
          "亳州",
        ],
      },
      {
        index: "C",
        data: [
          "重庆",
          "成都",
          "长沙",
          "长春",
          "沧州",
          "常德",
          "昌都",
          "长治",
          "常州",
          "巢湖",
          "潮州",
          "承德",
          "郴州",
          "赤峰",
          "池州",
          "崇左",
          "楚雄",
          "滁州",
          "朝阳",
        ],
      },
      {
        index: "D",
        data: [
          "大连",
          "东莞",
          "大理",
          "丹东",
          "大庆",
          "大同",
          "大兴安岭",
          "德宏",
          "德阳",
          "德州",
          "定西",
          "迪庆",
          "东营",
        ],
      },
      {
        index: "E",
        data: ["鄂尔多斯", "恩施", "鄂州"],
      },
      {
        index: "F",
        data: ["福州", "防城港", "佛山", "抚顺", "抚州", "阜新", "阜阳"],
      },
      {
        index: "G",
        data: [
          "广州",
          "桂林",
          "贵阳",
          "甘南",
          "赣州",
          "甘孜",
          "广安",
          "广元",
          "贵港",
          "果洛",
        ],
      },
      {
        index: "H",
        data: [
          "杭州",
          "哈尔滨",
          "合肥",
          "海口",
          "呼和浩特",
          "海北",
          "海东",
          "海南",
          "海西",
          "邯郸",
          "汉中",
          "鹤壁",
          "河池",
          "鹤岗",
          "黑河",
          "衡水",
          "衡阳",
          "河源",
          "贺州",
          "红河",
          "淮安",
          "淮北",
          "怀化",
          "淮南",
          "黄冈",
          "黄南",
          "黄山",
          "黄石",
          "惠州",
          "葫芦岛",
          "呼伦贝尔",
          "湖州",
          "菏泽",
        ],
      },
    ];
    return {
      code: 0,
      msg: "获取通讯录成功",
      data: { list },
    };
  } catch (err) {
    throw {
      code: 500,
      msg: "获取通讯录失败",
    };
  }
}
/**
 * 获取通知消息列表
 * @return {promise<{code:string,msg:string}>}
 */
async function GetNoticeMessageList(Request) {
  try {
    let list = [
      {
        id: 0,
        image:
          "https://ccdn1.goodq.top/caches/82fee4717198948d6253764710980ee2/aHR0cHM6Ly93d3cueTNxLm5ldC9xZnktY29udGVudC91cGxvYWRzLzIwMjEvMDYvZWQyZTM2NjE1OTM5YTM5NTY4YWJiM2Q2N2Q0NjYzMWItMTcweDE3MC5wbmc_p_p100_p_3D.png",
        name: "消息Tab1",
      },
      {
        id: 1,
        image:
          "https://ccdn1.goodq.top/caches/82fee4717198948d6253764710980ee2/aHR0cHM6Ly93d3cueTNxLm5ldC9xZnktY29udGVudC91cGxvYWRzLzIwMjEvMDYvNjI5YzUxOTg3NmM0NjFhYzg0MmYxMjE1OTBiMjVkMGUtMTcweDE3MC5wbmc_p_p100_p_3D.png",
        name: "消息Tab2",
      },
      {
        id: 2,
        image:
          "https://ccdn1.goodq.top/caches/82fee4717198948d6253764710980ee2/aHR0cHM6Ly93d3cueTNxLm5ldC9xZnktY29udGVudC91cGxvYWRzLzIwMjEvMDYvZmNlYTE0OTJiODMwMTA5MTEwOTNkYjc1ZGU4OWNkMjgtMTcweDE3MC5wbmc_p_p100_p_3D.png",
        name: "消息Tab3",
      },
      {
        id: 3,
        image:
          "https://ccdn1.goodq.top/caches/82fee4717198948d6253764710980ee2/aHR0cHM6Ly93d3cueTNxLm5ldC9xZnktY29udGVudC91cGxvYWRzLzIwMjEvMDYvYjgyYjZkMGJlZDFhMzRhMTJhODA4ZWJkYjlhMTNiYjMtMTcweDE3MC5wbmc_p_p100_p_3D.png",
        name: "消息Tab4",
      },
    ];
    return {
      code: 0,
      msg: "获取成功",
      data: {
        list,
      },
    };
  } catch (error) {
    throw {
      code: 500,
      msg: "获取通知列表失败",
    };
  }
}
/**
 * 查看通知消息
 * @return {promise<{code:string,msg:string}>}
 */
async function lookNoticeMessage() {
  try {
    let { user, id } = params;
  } catch (error) {
    throw {
      code: 500,
      msg: "修改失败",
    };
  }
}
/**
 * 清除所有通知消息未读状态
 * @return {promise<{code:string,msg:string}>}
 */
async function lookAllNoticeMessage() { }
/**
 * 拉黑用户
 * @return {promise<{code:string,msg:string}>}
 */
async function BlackUser(Request) {
  try {
    let user = Request.$user;

    let body = Request.body;

    let to_black_user = body.to_black_user;

    await Redis.rPush(
      `${ProjectName}:user:blackList:${user}`,
      JSON.stringify({
        user: to_black_user,
        created_time: null,
      })
    );

    return { code: 0, msg: "拉黑成功" };
  } catch (error) {
    throw error;
  }
}
/**
 * 取消拉黑 / 删除拉黑
 * @return {promise<{code:string,msg:string}>}
 */
async function deleteBlackUser(Request) {
  try {
    let user = Request.$user;

    let body = Request.body;

    let to_black_user = body.to_black_user;
    // 获取MYSQL 实例
    let conn = await MYSQL.promise().getConnection();

    // 删除数据
    await conn.query(
      `
            DELETE FROM ${BlackUserSqlName} WHERE user = ${user} AND black_user = ${to_black_user}
            `
    );
    // 查询完毕，释放池连接回池
    await conn.release();
    return { code: 0, msg: "取消成功" };
  } catch (error) {
    throw error;
  }
}
/**
 * 黑名单列表
 * @return {promise<{code:string,msg:string}>}
 */
async function BlackUserList(Request) { }
/**
 * 查询用户Websocket是否在线
 * @param {String} user 传入用户id
 */
async function WebsocketIfLine(user) {
  try {
    if (!user) {
      throw { code: 500, msg: "获取在线状态失败" };
    }
    // 将Redis中存储的在线状态清楚
    let RedisPath = `${ProjectName}:user:Online:${user}`;
    let status = await Redis.get(RedisPath);
    let onLineStatus = Boolean(Number(status));
    return onLineStatus;
  } catch (error) {
    throw { code: 500, msg: "获取在线状态失败" };
  }
}
/**
 * 用户接入Websocket服务
 * @param {String} user 传入用户id
 * @return {promise<{code:string,msg:string}>}
 */
async function LineWebsocket(user) {
  try {
    if (!user) {
      return;
    }
    // 将Redis中存储的在线状态清楚
    // let RedisPath = `${ProjectName}:user:Online:${user}`
    // await Redis.hSet(RedisPath, "ip", 1)
    // await Redis.hSet(RedisPath, "device", 1)
    // await Redis.hSet(RedisPath, "created_time", 1)
    // await Redis.hSet(RedisPath, "state", 1)
    return { code: 0, msg: "操作成功" };
  } catch (error) {
    throw { code: 500, msg: "操作失败" };
  }
}
/**
 * 保存我的位置
 * @return {promise<{code:string,msg:string}>}
 */
async function PushMyLocation(Request) {
  try {
    let Body = Request.body;
    let { longitude, latitude } = Body;
    let user = Request.$user;
    let data = {
      longitude,
      latitude,
    };
    // 存入Redis
    await Redis.hset(`${ProjectName}:user:${user}:location:Info`, data);
    await Redis.lpush(`${ProjectName}:user:${user}:location:Log:List`, data);
    return {
      code: 0,
      msg: "操作成功",
      data,
    };
  } catch (e) {
    console.log(e);
    throw {
      code: 500,
      msg: "操作失败",
    };
  }
}
/**
 * 用户断开Websocket服务
 * @param {String} user 传入用户id
 * @return {promise<{code:string,msg:string}>}
 */
async function LineWebsocketClose(user) {
  try {
    if (!user) {
      return;
    }
    // 将Redis中存储的在线状态清楚
    let RedisPath = `${ProjectName}:user:Online:${user}`;
    await Redis.del(RedisPath);
    return { code: 0, msg: "操作成功" };
  } catch (error) {
    throw { code: 500, msg: "操作失败" };
  }
}
/**
 * 申请添加好友
 * @param {String} AddUser 传入用户id
 * @return {promise<{code:string,msg:string}>}
 */
async function AddFriend(Request) {
  try {
    let user = Request.$user;
    let body = Request.body;
    let AddUser = body.AddUser;
    if (user == AddUser) {
      throw { code: 500, msg: "不能添加自己为好友" };
    }
    let RedisPath = `${ProjectName}:user:Friend:${user}:Request`;
    await Redis.rPush(
      RedisPath,
      JSON.stringify({
        user: AddUser,
        request_time: 1,
      })
    );
    return true;
  } catch (error) {
    throw error;
  }
}
/**
 * 拒绝添加好友
 * @return {promise<{code:string,msg:string}>}
 */

/**
 * 好友列表
 * @param {Number} page 页码
 * @return {promise<{code:string,msg:string}>}
 */
async function FriendList(Request) {
  try {
    let user = Request.$user;

    let query = Request.query;

    let { page } = query;

    let RedisPath = `${ProjectName}:user:Friend:${user}:List`;
    // 分页Redis 查询
    let list = await Redis.lRange(RedisPath, 0, -1);
    return {
      code: 0,
      msg: "操作成功",
      data: {
        page,
        list,
      },
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 同意好友申请
 * @return {promise<{code:string,msg:string}>}
 */
async function AgreeFriend(Request) { }
/**
 * 删除好友
 * @return {promise<{code:string,msg:string}>}
 */
async function DeleteFriend(Request) { }
/**
 * 拉黑好友
 * @return {promise<{code:string,msg:string}>}
 */
async function BlackFriend(Request) { }

/**
 * 消息置顶设置
 * @return {promise<{code:string,msg:string}>}
 */
async function TopMessage(Request) { }
/**
 * 阅读消息
 * @return {promise<{code:string,msg:string}>}
 */
async function readMessage(Request) { }
/**
 * 附近
 * @return {promise<{code:string,msg:string}>}
 */
async function GetNearbyList(Request) { }
module.exports = {
  PushMyLocation,
  GetNearbyList,
  KickMember,
  DisbandGroup,
  CreatedGroup,
  CreatedGroupMessage,
  deleteBlackUser,
  GetInfo,
  BlackUser,
  GetMessageHistory,
  GetMessageList,
  GetNoticeMessageList,
  GetMailList,
  SendMessage,
  deleteAddress,
  AddAddress,
  AddressList,
  EmptyAddress,
  SetDefaultAddress,
  UpdateAddress,
  Login,
  CheckToken,
  loginout,
  UpdateInfo,
  GetErase,
  CancelErase,
  Erase,
};
